<template>
  <div class="item">
    <el-form ref="form"
             :rules="rules"
             :model="item">
      <el-form-item>
        <el-select v-model="item.type"
                   class="fl"
                   @change="typeChange"
        >
            <!-- 完成，取消步骤不显示 -->
            <el-option
              v-for="(item, index) in oprateOptions"
              :key="index"
              :label="operateMap[item]"
              :value="item">
            </el-option>
        </el-select>
        <span class="prompt" v-if="item.type === 'sendMessage'" style="padding-left: 15px">{{$t('config.business.tip')}}</span>
        <span class="prompt" v-if="item.type === 'sendSatisfaction'" style="padding-left: 15px">{{$t('config.business.tip1')}}</span>
        <template v-if="item.type === 'assign'">
          <el-form-item prop="agent" class="fl" style="margin: 0 15px">
            <el-select v-model="item.agent"
                       :filterable="true"
                       key="assign"
            >
              <el-option
                v-for="(item, index) in agentList"
                :key="index"
                :label="item.label"
                :value="item.value">
              </el-option>
              <el-option v-for="item in unAgentList" :label="item.label" :value="item.label" :key="item._id" style="display:none;height:0;width:0;"></el-option>
            </el-select>
          </el-form-item>
          <el-checkbox v-model="item.leaveNot">{{$t('config.business.tip2')}}</el-checkbox>
        </template>
      </el-form-item>
      <template v-if="item.type === 'sendSatisfaction'">
          <el-form-item prop="agent" class="item-select">
          <el-select v-model="item.agent"
                     :placeholder="$t('config.business.recipient')"
                     size="small"
                     :filterable="true"
                     collapse-tags
                     style="width: 100%"
          >
            <slot-filter>
              <el-option
                :label="$t('business.businessCreate')"
                value="creator">
              </el-option>
              <el-option
                v-show="eventType === 'back'"
                :label="$t('business.preAgent')"
                value="lastMaster">
              </el-option>
              <el-option
                :label="$t('public.customer')"
                value="customer">
              </el-option>
              <el-option
                v-for="item in allAgent"
                :key="item.key"
                :label="item.name"
                :value="item.key">
              </el-option>
            </slot-filter>
          </el-select>
        </el-form-item>
        <div class="prompt">
          {{$t('config.business.tip3')}}
        </div>
        <el-form-item prop="notify" class="item-select">
          <el-select v-model="item.notify"
                     :placeholder="$t('config.business.sendFailureAlertPerson')"
                     :multiple="true"
                     :filterable="true"
                     size="small"
                     collapse-tags
                     style="width: 100%;"
                     class="item-select"
          >
            <slot-filter>
              <el-option
                :label="$t('business.businessCreate')"
                value="creator">
              </el-option>
              <el-option
                :label="masterLabel"
                value="master">
              </el-option>
              <el-option
                v-for="item in allAgent"
                :key="item.key"
                :label="item.name"
                :value="item.key">
              </el-option>
            </slot-filter>
          </el-select>
        </el-form-item>
        <div class="prompt">
          {{$t('config.business.tip8')}}
        </div>
      </template>
      <template v-if="item.type === 'sendMail' && !mailId">
        <div class="config">
            <span v-if="this.powerList.indexOf('simple_notification_mail_config') === -1">{{$t('config.business.tip6')}}</span>
            <span v-else> {{$t('config.business.tip4')}}<router-link to="/index/newConfig/emailNotify?active=enterpriseMail">{{$t('config.business.tip5')}}</router-link></span>
        </div>
      </template>
      <template v-if="item.type === 'sendMail' && mailId">
        <el-form-item prop="to">
          <el-checkbox-group v-model="item.mailType" @change="mailTypeChange">
            <el-checkbox label="stable">
              {{$t('config.business.internalReceiver')}}
            </el-checkbox>
            <el-checkbox label="custom">
              {{$t('config.business.customizingRecipients')}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <template v-if="item.mailType.indexOf('stable') !== -1">
        <el-form-item prop="to" class="item-select">
          <el-select v-model="item.to"
                     :placeholder="$t('config.business.recipient')"
                     :multiple="true"
                     size="small"
                     :filterable="true"
                     collapse-tags
                     style="width: 100%"
          >
            <slot-filter>
              <el-option
                :label="$t('business.businessCreate')"
                value="creator">
              </el-option>
              <el-option
                :label="masterLabel"
                value="master">
              </el-option>
              <el-option
                v-show="eventType === 'back'"
                :label="$t('business.preAgent')"
                value="lastMaster">
              </el-option>
              <el-option
                :label="$t('public.customer')"
                value="customer">
              </el-option>
              <el-option
                v-for="item in allAgent"
                :key="item.key"
                :label="item.name"
                :value="item.key">
              </el-option>
            </slot-filter>
          </el-select>
        </el-form-item>
        <el-form-item prop="cc" class="item-select">
                    <el-select v-model="item.cc"
                     :placeholder="$t('email.copyFor2')"
                     :multiple="true"
                     size="small"
                     :filterable="true"
                     collapse-tags
                     style="width: 100%"
          >
            <slot-filter>
              <el-option
                :label="$t('business.businessCreate')"
                value="creator">
              </el-option>
              <el-option
                :label="masterLabel"
                value="master">
              </el-option>
              <el-option
                :label="$t('public.customer')"
                value="customer">
              </el-option>
              <el-option
                v-for="item in allAgent"
                :key="item.key"
                :label="item.name"
                :value="item.key">
              </el-option>
            </slot-filter>
          </el-select>
        </el-form-item>
      </template>
        <template v-if="item.mailType.indexOf('custom') !== -1">
          <el-form-item prop="customTo">
            <el-input v-model.trim="item.customTo" :placeholder="$t('config.business.customizingRecipients')"></el-input>
          </el-form-item>
          <div class="prompt">
            {{$t('config.business.tip7')}}
          </div>
          <el-form-item prop="customCc">
            <el-input v-model.trim="item.customCc" :placeholder="$t('config.business.customCc')"></el-input>
          </el-form-item>
          <div class="prompt">
            {{$t('config.business.tip7')}}
          </div>
        </template>
        <el-form-item prop="notify" class="item-select">
          <el-select v-model="item.notify"
                     :placeholder="$t('config.business.sendFailureAlertPerson')"
                     :multiple="true"
                     :filterable="true"
                     size="small"
                     collapse-tags
                     style="width: 100%;"
                     class="item-select"
          >
            <slot-filter>
              <el-option
                :label="$t('business.businessCreate')"
                value="creator">
              </el-option>
              <el-option
                :label="masterLabel"
                value="master">
              </el-option>
              <el-option
                v-for="item in allAgent"
                :key="item.key"
                :label="item.name"
                :value="item.key">
              </el-option>
            </slot-filter>
          </el-select>
        </el-form-item>
        <div class="prompt">
          {{$t('config.business.tip8')}}
        </div>
        <el-form-item prop="templateId" class="item-select">
          <el-select v-model="item.templateId"
                     :placeholder="$t('config.business.selectTemplate')"
                     :filterable="true"
                     style="width: 100%;"
                     class="item-select"
          >
            <el-option
              v-for="item in mailTemplateList"
              :key="item._id"
              :label="item.name"
              :value="item._id">
            </el-option>
          </el-select>
        </el-form-item>
        <div class="content-html" v-html="smsTemp.content" style="margin-bottom: 10px">
        </div>
      </template>
      <template v-if="item.type === 'sendSms'">
        <el-form-item prop="agent" class="item-select">
          <el-select v-model="item.agent"
                     :placeholder="$t('config.business.recipient')"
                     :multiple="true"
                     size="small"
                     :filterable="true"
                     collapse-tags
                     style="width: 100%"
          >
            <slot-filter>
              <el-option
                :label="$t('business.businessCreate')"
                value="creator">
              </el-option>
              <el-option
                :label="masterLabel"
                value="master">
              </el-option>
              <el-option
                v-show="eventType === 'back'"
                :label="$t('business.preAgent')"
                value="lastMaster">
              </el-option>
              <el-option
                v-show="currentStep.type !== 'sys' && eventType === 'shift'"
                :label="$t('business.nextMaster')"
                value="nextMaster">
              </el-option>
              <el-option
                :label="$t('public.customer')"
                value="customer">
              </el-option>
              <el-option
                v-for="item in allAgent"
                :key="item.key"
                :label="item.name"
                :value="item.key">
              </el-option>
            </slot-filter>
          </el-select>
        </el-form-item>
        <div class="prompt">
          {{$t('config.business.tip3')}}
        </div>
        <el-form-item prop="notify" class="item-select">
          <el-select v-model="item.notify"
                     :placeholder="$t('config.business.sendFailureAlertPerson')"
                     :multiple="true"
                     :filterable="true"
                     size="small"
                     collapse-tags
                     style="width: 100%;"
                     class="item-select"
          >
            <slot-filter>
              <el-option
                :label="$t('business.businessCreate')"
                value="creator">
              </el-option>
              <el-option
                :label="masterLabel"
                value="master">
              </el-option>
              <el-option
                v-for="item in allAgent"
                :key="item.key"
                :label="item.name"
                :value="item.key">
              </el-option>
            </slot-filter>
          </el-select>
        </el-form-item>
        <div class="prompt">
           {{$t('config.business.tip9')}}
        </div>
        <el-form-item prop="templateId" class="item-select">
          <el-select v-model="item.templateId"
                     :placeholder="$t('config.business.selectTemplate')"
                     :filterable="true"
                     style="width: 100%;"
                     class="item-select"
          >
            <el-option
              v-for="item in smsTemplate"
              :key="item._id"
              :label="item.name"
              :value="item._id">
            </el-option>
          </el-select>
        </el-form-item>
        <div class="content">
          {{smsTemp.content || $t('config.business.selectTemplateAfter')}}
        </div>
      </template>
      <template v-else-if="item.type === 'sendMessage'">
        <el-form-item prop="agent" class="item-select">
          <el-select v-model="item.agent"
                     :multiple="true"
                     :filterable="true"
                     size="small"
                     collapse-tags
                     style="width: 100%"
                     class="item-select"
                     :placeholder="$t('config.business.recipient')"
          >
            <slot-filter>
              <el-option
                :label="$t('business.businessCreate')"
                value="creator">
              </el-option>
              <el-option
                :label="masterLabel"
                value="master">
              </el-option>
              <el-option
                v-show="eventType === 'back'"
                :label="$t('business.preAgent')"
                value="lastMaster">
              </el-option>
              <el-option
                v-for="item in allAgent"
                :key="item.key"
                :label="item.name"
                :value="item.key">
              </el-option>
            </slot-filter>
          </el-select>
        </el-form-item>
        <div class="content">
          {{$t('configLazyLoad.businessConfig.triggerMessageTemplate')}}
          <!-- triggerMessageTemplate -->
        </div>
        <!-- <div class="content" v-else>
          工单｛ticket.field_num｝被 【退回操作执行人】退回
        </div> -->
      </template>
      <el-collapse style="border: none;" class="collapse-item" v-show="item.type === 'sendSms' || item.type === 'sendMessage'">
        <el-collapse-item :title="$t('config.business.viewAvailablePlaceholders')" name="1" class="el-collapse-item">
          {{$t('configLazyLoad.businessConfig.placeholderTip')}}<br>
          {{$t('config.business.repairOrderField')}}<br>
          {{$t('config.business.businessNumber')}}<br>
          {ticket.field_num}<br>
          {{$t('config.business.triggerHeading')}}<br>
          {task_name}<br>
        </el-collapse-item>
      </el-collapse>
    </el-form>
  </div>
</template>

<script>
  import {update, filterXSS} from '../../../../../utils/m7Utils'
  import slotFilter from './slotFilter'
  import API from '../../../../../store/api/config/emailNotify'
  import {strToArr} from '../../../../../utils/workflowUtils'
  import {checkform} from '@/utils/validate.js'
  export default {
    name: 'operate-item',
    data () {
      let validate1 = (rule, value, callback) => {
        let mailArr = strToArr(value) || []
        let inValid = mailArr.some((item, index) => {
          if (checkform(item, 'Email')) {
            callback(`第${index + 1}个邮箱格式错误`)
            return true
          }
        })
        if (!inValid) {
          callback()
        }
      }
      return {
        smsTemplate: [],
        // 分配，通知，短信三种类型的默认数据
        baseForm: {
          assign: {type: 'assign', agent: '', leaveNot: false},
          sendSms: {type: 'sendSms', agent: [], notify: [], templateId: ''},
          sendSatisfaction: {type: 'sendSatisfaction', agent: '', notify: []},
          sendMessage: {type: 'sendMessage', agent: []},
          sendMail: {type: 'sendMail', mailType: ['stable'], to: [], cc: [], templateId: '', mailId: '', customTo: '', customCc: '', notify: []},
        },
        mailTemplate: '',
        rules: {
          agent: [
            {required: true, message: this.$t('validate.required'), trigger: 'change'}
          ],
          templateId: [
            {required: true, message: this.$t('validate.required'), trigger: 'change'}
          ],
          customTo: [
            {required: false, validator: validate1, trigger: 'blur'}
          ],
          customCc: [
            {required: false, validator: validate1, trigger: 'blur'}
          ]
        },
        smsSign: [],
        unAgentList: [],
        agentList:[],
        operateMap: {
          sendMessage: this.$t('config.business.sendingMessageInside'),
          sendSms:  this.$t('config.business.sendingMessageSms'),
          sendSatisfaction: this.$t('config.business.sendSatisfactionSurvey'),
          assign: this.$t('config.business.assignToAgent'),
          sendMail: this.$t('config.business.sendingMessageEmail')
        }
      }
    },
    props: {
      item: {type: Object, default: function () { return {} }},
      allAgent: {type: Array, default: function () { return [] }},
      appraiseTemplates: {type: Array, default: function () { return [] }},
      defaultAgent: {type: Array, default: function () { return [] }},
      currentStep: {type: Object, default: function () { return {} }},
      eventType: {type: String, default: 'shift'},
      addTypes: {type: Array, default: function () { return [] }},
      mailTemplateList: {type: Array, default: function () { return [] }},
      mailId: {type: String, default: ''},
    },
    inject: {
      powerList: { default: [] }
    },
    components: {
      slotFilter
    },
    computed: {
      smsTemp () {
        if (this.item.type === 'sendSms') {
          let tmpl = this.smsTemplate.filter((item) => {
            return item._id === this.item.templateId
          })[0] || {}
          return Object.assign({}, tmpl)
        } else if (this.item.type === 'sendMail') {
          let tmpl = this.mailTemplateList.find((item) => {
            return item._id === this.item.templateId
          }) || {content: this.$t('config.business.selectTemplateAfter')}
          tmpl.content = filterXSS(tmpl.content)
          return tmpl
        }
        return {}
      },
      // 当前item的可选操作
      oprateOptions () {
        return [].concat([this.item.type], this.addTypes)
      },
      masterLabel () {
        return this.eventType === 'shift' ? this.$t('business.preAgent') : this.$t('business.master')
      }
    },
    watch: {
      'item.templateId' (cur) {
        if (this.item.type === 'sendSms') {
          this.templateChange()
        }
      }
    },
    methods: {
      typeChange (value, data) {
        update(this.item, this.baseForm[value], this)
        this.$refs.form.clearValidate()
      },
      submit () {
        let data = null
        console.log(this)
        this.$refs.form.validate((valid) => {
          if (valid) {
            // 校验成功，如果是短信，生成其他需要的数据
            if (this.item.type === 'sendSms') {
              let sms = {template: this.smsTemp.content, smsChannel: this.smsTemp.smsChannel[0]}
              for (let j = 0; j < this.smsSign.length; j++) {
                if (this.smsTemp.sign === this.smsSign[j]._id) {
                  sms.templateSign = this.smsSign[j].subcode + '_' + this.smsSign[j].name
                }
              }
              data = Object.assign(this.item, sms)
            } else if (this.item.type === 'sendSatisfaction') {
              this.item.satisfactionId = this.appraiseTemplates[0] && this.appraiseTemplates[0]._id
              if (this.item.satisfactionId) {
                data = this.item
              } else {
                this.$message.error(this.$t('config.business.tip10'))
              }
            } else if (this.item.type === 'sendMail') {
              let {to, cc, customTo, customCc} = this.item
              if (!to.length && !cc.length && !customTo.length && !customCc.length) {
                this.$message.error(this.$t('config.business.tip11'))
                return
              }
              this.item.mailId = this.mailId
              data = this.item
            } else {
              data = this.item
            }
          }
        })
        return data
      },
      templateChange () {
        let isHas = this.smsTemplate.some((item) => {
          if (item._id === this.item.templateId) {
            return true
          }
        })
        if (this.item.type === 'sendSms' && this.item.templateId && !isHas) {
          this.$message.error(this.$t('config.business.tip12'))
          this.item.templateId = ''
        }
      },
      mailTypeChange (cur) {
        if (cur.indexOf('stable') === -1) {
          this.item.cc = []
          this.item.to = []
        }
        if (cur.indexOf('custom') === -1) {
          this.item.customCc = ''
          this.item.customTo = ''
        }
      }
    },
    beforeMount () {
      console.log(this.defaultAgent)
      this.defaultAgent.forEach(item=>{
        if(item.status == 'enable'){
          this.agentList.push(item)
        }else{
          this.unAgentList.push(item)
        }
      })
      this.$store.dispatch('getCache', {type: 'smsTemplate'}).then((res) => {
        this.smsTemplate = (res || []).filter((item) => item.type === 'flow')
        this.templateChange()
      })
      this.$store.dispatch('getCache', {type: 'smsSign'}).then((res) => {
        this.smsSign = res
      })
    }
  }
</script>

<style scoped lang='stylus'>
  @import '../../../../../assets/common.styl'
  .item
    display inline-block
    width: calc(100% - 30px)
  .item-select
    width 100%
    padding-right:5px
  .prompt
    color $c-prompt
    font-size 12px
    line-height 16px
  .content
    padding 15px
    font-size 12px
    line-height 16px
    background-color $c-back
    border-radius 5px
  .config
    line-height 36px
    margin-bottom 20px
    text-align center
    font-size 12px
    background-color #F4F5F9
  .content-html
    padding 15px
    font-size 12px
    line-height 1.5
    background-color $c-back
    border-radius 5px
    table
      border-top: 1px solid #ccc;
      border-left: 1px solid #ccc;
      td,th
        border-bottom: 1px solid #ccc;
        border-right: 1px solid #ccc;
        padding: 3px 5px;
      th
        border-bottom: 2px solid #ccc;
        text-align: center;
</style>
<style lang='stylus'>
  .collapse-item
    margin-bottom 1px
    .el-collapse-item__wrap
      border none
    .el-collapse-item__header
      border none
      font-size 12px
    .el-collapse-item__content
      font-size 12px
      border 1px solid #ccc
      padding 5px
</style>
